<template>
  <view class="container">


    <!-- 服务详情图 -->

    <view class="avatar">
      <span style="text-align: center;padding-top: 15px;">服务详情图</span>

      <!-- 上传组件 -->
      <u-upload name="product_img" :maxCount="6" :fileList="filelist2" width="100" height="100" @delete="del2"
        @afterRead="read2" />
    </view>



    <!-- 长图 -->
    <view class="avatar">
      <span>服务长图</span>

      <!-- 上传组件 -->
      <u-upload name="product_img" :maxCount="1" :fileList="filelist" width="100" height="100" @delete="del"
        @afterRead="read" />
    </view>

    <!-- 方图 -->
    <view class="avatar">
      <span>首页服务图(方图):</span>


      <!-- 上传组件 -->
      <u-upload name="product_img" :maxCount="1" :fileList="filelist1" width="100" height="100" @delete="del1"
        @afterRead="read1" />
    </view>

    <view class="content">
      <u-form labelPosition="left" labelWidth="60" :model="service" :rules="rules" ref="product">
        <!-- 部门 -->
        <u-form-item label="门店" prop="store.name" borderBottom @click="showstore = true">
          <u-input v-model="service.store.name" disabled disabledColor="#ffffff" placeholder="请选择所属门店"
            border="none"></u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <u-form-item label="推荐栏" borderBottom @click="showsellcolumn = true">
          <u-input v-model="service.sellcolumn_text" disabled disabledColor="#ffffff" placeholder="请选择是否推荐"
            border="none"></u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <!-- 品牌 -->
        <u-form-item label="类型" prop="type_text" borderBottom @click="showtype = true">
          <u-input v-model="service.type_text" disabled disabledColor="#ffffff" placeholder="请选择服务类型"
            border="none"></u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <!-- 名称 -->
        <u-form-item label="标题" prop="title">
          <u-input v-model="service.title" ref="title" placeholder="请输入商品名称" />
        </u-form-item>

        <!-- 商品描述 -->
        <u-form-item label="简介" prop="content" borderBottom>
          <u-textarea placeholder="不低于3个字" v-model="service.content" count></u-textarea>
        </u-form-item>

        <!-- 全款 -->
        <u-form-item label="服务费用" prop="free">
          <u-input v-model="service.free" placeholder="请填写服务费用" />
        </u-form-item>

        <u-form-item label="员工比例" prop="emptcbili" v-if="auth.tcbili_text == 1 || auth.id == 1">
          <u-input min="0.00" v-model="service.emptcbili" placeholder="请输入员工提成比例" />
        </u-form-item>
        <u-form-item label="员工提成" prop="empcommission" v-if="auth.tcbili_text == 1 || auth.id == 1">
          <u-input v-model="service.empcommission" placeholder="请输入员工提成" />
        </u-form-item>

        <u-form-item label="平台比例" prop="pttcbili" v-if="auth.tcbili_text == 1 || auth.id == 1">
          <u-input min="0.00" v-model="service.pttcbili" placeholder="请输入平台提成比例" />
        </u-form-item>
        <u-form-item label="平台提成" prop="ptcommission" v-if="auth.tcbili_text == 1 || auth.id == 1">
          <u-input v-model="service.ptcommission" placeholder="请输入平台提成" />
        </u-form-item>

        <u-action-sheet :show="showstore" :actions="stolist" title="请选所属的门店" @close="showstore = false"
          @select="storeSelect()">
        </u-action-sheet>
        <u-action-sheet :show="showtype" :actions="typelist" title="请选所属服务分类" @close="showtype = false"
          @select="typeSelect()">
        </u-action-sheet>
        <u-action-sheet :show="showsellcolumn" :actions="sellcolumnlist" title="请选择是否为推荐"
          @close="showsellcolumn = false" @select="sellcolumnSelect()" />

        <!-- <u-popup :customStyle="custom-style" :show="showtype" @close="close" mode="bottom" closeIconPos="top-right" closeable="true">
					<view>
						<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" >
							<view v-for="item in typelist" :key="item.id">
								<view class="typestyle">{{item.name}}</view>
							</view>
						</scroll-view>
					</view>
				</u-popup> -->

        <!-- 提交按钮 -->
        <u-button text="添加服务" icon="pushpin" size="small" type="primary" :customStyle="btnStyle"
          @click="product(typeid)" />
      </u-form>
    </view>
    <!-- 消息提醒 -->
    <u-toast ref="notice"></u-toast>
  </view>
</template>

<script>
export default {
  onLoad(option) {
    this.auth = this.$u.auth.check();

    this.storelist();

    this.typedata();
    this.typeid = option.typeid ? option.typeid : 0;
  },

  onReady() {
    this.$refs.product.setRules(this.rules);
  },
  created() {
    this.timer = setInterval(() => {
      let a = this.$u.count.check();
    }, 15000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  data() {
    return {
      showsellcolumn: false,
      sellcolumnlist: [
        {
          sellcolumn: 0,
          name: "正常",
        },
        {
          sellcolumn: 1,
          name: "推荐",
        },
      ],
      typeid: 0,
      scrollTop: 10,
      showtype: false,
      filelist: [],
      filelist1: [],
      newthumbArr: [],
      filelist2: [],
      showstore: false,
      auth: {},
      vediolist: [],
      serid: 0,
      store_text: "",
      stoid: null,
      stolist: [],
      thumbs_text: "",
      name: "",
      service: {
        squareImage: "",
        image_text: "",
        imagelist_text: "",
        typeid: "",
        store: {
          name: "",
        },
      },
      // customStyle:{
      // 	height:"400px"
      // },
      piclist: [],
      content: "",
      typelist: [],
      free: 0,
      rules: {
        content: {
          required: true,
          message: "不低于3个字",
          trigger: ["change"],
        },
        "store.name": {
          required: true,
          message: "请选择你所属的门店",
          trigger: ["blur", "change"],
        },
        type_text: {
          required: true,
          message: "请选择服务类型",
          trigger: ["blur", "change"],
        },
        title: {
          required: true,
          message: "请填写服务标题",
          trigger: ["blur", "change"],
        },
        free: {
          required: true,
          message: "服务费用不能为空",
          trigger: ["blur", "change"],
        },
        emptcbili: {
          required: true,
          message: "员工提成比例不能为空",
          trigger: ["blur", "change"],
        },
        bustcbili: {
          required: true,
          message: "客户提成比例不能为空",
          trigger: ["blur", "change"],
        },
        pttcbili: {
          required: true,
          message: "平台提成比例不能为空",
          trigger: ["blur", "change"],
        },
      },
    };
  },
  computed: {
    //提成计算
    commission() {
      if (this.service.free != "" || this.service.free != 0.0) {
        // 员工提成
        if (this.service.emptcbili > 1) {
          this.$refs.notice.show({
            type: "warning",
            message: "员工提成比率不能大于1",
            duration: 1200,
          });
        } else {
          this.service.empcommission =
            this.service.free * this.service.emptcbili;
        }

        // 平台提成
        if (this.service.pttcbili > 1.0) {
          this.$refs.notice.show({
            type: "warning",
            message: "平台提成比率不能大于1",
            duration: 1200,
          });
        } else {
          this.service.ptcommission = this.service.free * this.service.pttcbili;
        }

        let empcom = this.service.empcommission;

        let ptcom = this.service.ptcommission;

        let countnum = empcom + ptcom;

        // parseFloat转化成浮点数
        let a = parseFloat(countnum);

        //计算提成总金额（相加的提成金额，大于租车总额）
        if (a > parseFloat(this.service.free)) {
          this.$refs.notice.show({
            type: "error",
            message: "分配的提成已超出租金总额，分成失败",
            duration: 20000,
          });
        }

        return this.service.empcommission, this.service.ptcommission;
      }
    },
  },

  methods: {

    sellcolumnSelect(e) {
      this.service.sellcolumn_text = e.name;
      this.service.sellcolumn = e.sellcolumn;
    },


    product(e) {
      let urlArray = this.filelist2.map(item => item.url);

      this.$refs.product
        .validate()
        .then(async () => {
          var data = {
            stoid: this.service.stoid,
            title: this.service.title,
            free: this.service.free,
            adminid: this.auth.id,
            image: this.service.image_text,
            content: this.service.content,
            typeid: this.service.typeid,
            sellcolumn: this.service.sellcolumn,
            squareImage: this.service.squareImage,
            imagelist: urlArray,
            pttcbili: this.service.pttcbili,
            ptcommission: this.service.ptcommission,
            bustcbili: this.service.bustcbili,
            buscommission: this.service.buscommission,
            emptcbili: this.service.emptcbili,
            empcommission: this.service.empcommission,
            newthumbArr: this.newthumbArr
          };

          let result = await this.$u.api.product.servicesadd(data);

          if (result.code) {
            this.$refs.notice.show({
              type: "success",
              message: result.msg,
              duration: 1200,
              complete: () => {
                //返回上一个界面
                uni.$u.route({
                  type: "redirectTo",
                  url: "/pagesC/product/gsservices/servicelist/list",
                  params: {
                    typeid: this.typeid
                  }
                })
              },
            });
          } else {
            this.$refs.notice.show({
              type: "error",
              message: result.msg,
              duration: 1000,
            });
          }
        })
        .catch(() => {
          uni.$u.toast("效验失败");
        });
    },
    async storelist() {
      let data = {
        adminid: this.auth.id,
        stoid: this.auth.stoid,
      };
      let result = await this.$u.api.product.storelist(data);

      if (result.code) {
        this.stolist = result.data;
      } else {
        this.$refs.notice.show({
          type: "error",
          message: result.msg,
        });
      }
    },
    async typedata() {
      let data = {
        adminid: this.auth.id,
        stoid: this.auth.stoid,
      };
      let result = await this.$u.api.product.typelist(data);

      if (result.code) {
        this.typelist = result.data;
      } else {
        this.$refs.notice.show({
          type: "error",
          message: result.msg,
        });
      }
    },
    async read2(event) {
      //组装上传数据
      var data = {
        filePath: event.file.thumb,
        name: "product_img",
        header: {},
      };

      //调用接口
      var result = await this.$u.api.product.thumbs(data);

      if (result.code) {
        // 合并对象
        this.filelist2 = this.filelist2.concat({ url: result.data });
        this.newthumbArr = this.newthumbArr.concat(result.data)


        let userArray = Object.entries(this.filelist2).map(([key, value]) => {
          return { value }

        });

        userArray.forEach((item) => {
          // 截取想要部分路径
          let str = item.value.url.slice(item.value.url);

          // 把想要的路径追加到数组
          this.piclist.push(str);
        });
        // 数组的去重
        let qcarr = [...new Set(this.piclist)];

        // 数组转化成字符串
        this.service.imagelist_text = qcarr.join(",");
      } else {
        this.$refs.notice.show({
          type: "error",
          message: result.msg,
        });
        return false;
      }
    },
    async read(event) {
      //组装上传数据
      var data = {
        filePath: event.file.thumb,
        name: "product_img",
        header: {},
      };

      //调用接口
      var result = await this.$u.api.product.thumbs(data);

      if (result.code) {
        this.service.image_text = result.data;
        // 合并对象
        this.newthumbArr = this.newthumbArr.concat(result.data)

        this.filelist = [{ url: result.data }];
        return false;
      } else {
        this.$refs.notice.show({
          type: "error",
          message: result.msg,
        });
        return false;
      }
    },
    async read1(event) {
      //组装上传数据
      var data = {
        filePath: event.file.thumb,
        name: "product_img",
        header: {},
      };

      //调用接口
      var result = await this.$u.api.product.thumbs(data);

      if (result.code) {
        this.service.squareImage = result.data;
        // 合并对象
        this.filelist1 = [{ url: result.data }];
        this.newthumbArr = this.newthumbArr.concat(result.data)

        return false;
      } else {
        this.$refs.notice.show({
          type: "error",
          message: result.msg,
        });
        return false;
      }
    },


    async del(e) {
      let data = {
        adminid: this.auth.id,
        serid: this.serid,
        url: e.file.url,
      };

      var result = await this.$u.api.product.delimage(data);

      if (result.code) {
        this.$refs.notice.show({
          type: "success",
          message: result.msg,
          duration: 1000,
          complete: () => {

            this.filelist = [];
            this.service.image_text = ""

          },
        });
      } else {
        this.$refs.notice.show({
          type: "error",
          message: result.msg,
          duration: 1000,
        });
      }
    },
    del2(e) {
      this.filelist2.map(async (item, index) => {

        if (index == e.index) {
          // 删除数组中的某一项

          let data = {
            serid: this.serid,
            url: e.file.url,
          };
          var result = await this.$u.api.product.delimagelist(data);

          if (result.code) {
            this.$refs.notice.show({
              type: "success",
              message: result.msg,
              duration: 500,
              complete: () => {
                this.filelist2.splice(e.index, index);

                // 图片还剩余一张的时候清空
                if (index == 0 && e.index == 0) {
                  this.filelist2 = [];
                }
              },
            });
            return false;
          } else {
            this.$refs.notice.show({
              type: "success",
              message: result.msg,
              duration: 600,
              complete: () => {
                this.filelist2 = []
              }

            })
          }
        }
      });
    },
    async del1(e) {
      let data = {
        adminid: this.auth.id,
        serid: this.serid,
        url: e.file.url,
      };

      var result = await this.$u.api.product.delsquareImage(data);

      if (result.code) {
        this.$refs.notice.show({
          type: "success",
          message: result.msg,
          duration: 1000,
          complete: () => {

            this.filelist1 = [];
            this.service.squareImage = ""

          },
        });
      } else {
        this.$refs.notice.show({
          type: "error",
          message: result.msg,
          duration: 1000,
        });
      }
    },

    storeSelect(e) {
      this.service.store.name = e.name;
      this.service.stoid = e.id;
    },
    typeSelect(e) {
      this.service.type_text = e.name;
      this.service.typeid = e.id;
    },
  },
};
</script>

<style>
.content {
  padding: 20px;
}

.container {
  height: 100%;
  margin: 0 50rpx;
  box-sizing: border-box;
}

.avatar {
  text-align: center;
}

.u-avatar {
  margin: 80rpx auto 40rpx;
}

.xcx {
  width: 200rpx;
  height: 200rpx;
  margin: 80rpx auto 40rpx;
  border-radius: 100%;
  overflow: hidden;
}

.nickname {
  font-size: 14px;
  text-align: center;
}

.title {
  text-align: center;
  margin: 40rpx 0;
  font-size: 14rpx;
}

.avatar .u-upload {
  justify-content: center;
  align-items: center;
  margin: 3em auto;
}

.typestyle {
  text-align: center;
}

.scroll-Y {
  height: 300rpx;
}
</style>